/**
 * Copyright (C) 2010 Neofonie GmbH
 *
 * This programm is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.dicode.analysis.demonstrator.service;

import eu.dicode.analysis.demonstrator.model.TopicCommand;
import eu.dicode.analysis.demonstrator.util.Configuration;
import eu.dicodeproject.analysis.xsd.topics.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.LockableFileWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.xml.bind.JAXBException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * The DICODE twitter analysis is based on tracking tweets belonging to a particular
 * topic. Each topic is made up of a series of queries sent to twitter regularly. This
 * service provides a means to change the composition of queries representing any single
 * topic.
 *
 * Implements a service component for storing and loading topic configurations from disk.
 * Configurations are stored to and loaded from xml files.
 */
@Component
@Scope("singleton")
public class ConfigruationBasedTopicService implements TopicService {
  /** Logger of this class. */
  private static final Logger LOG = LoggerFactory.getLogger(ConfigruationBasedTopicService.class);
  /** List of topics already configured for tracking. */
  private final Map<String, TopicCommand> topicCommands = new ConcurrentHashMap<String, TopicCommand>();
  /** Name of the file to store topic configurations to. */
  private final String topicFilename;
  /** Link to configuration.*/
  private final String lockFile;

  /**
   * Init via constructor only to avoid stepping on ones own feet by resetting the filename internally
   * if non-final.
   * */
  public ConfigruationBasedTopicService() {
    Configuration configuration = Configuration.getInstance();

    this.topicFilename = configuration.getStringValue(
        Configuration.DICODE_TOPIC_LOCATION,
        Configuration.DICODE_DEFAULT_TOPIC_LOCATION);

    this.lockFile = configuration.getStringValue(
        Configuration.DICODE_TOPIC_LOCK_LOCATION,
        Configuration.DICODE_DEFAULT_TOPIC_LOCK_LOCATION);
  }

  /**{@inheritDoc}*/
  @Override
  public void addTopic(final TopicCommand topic) {
    TopicCommand newTopic = new TopicCommand(topic);
    put(topic);
    updateTopics();
  }

  /**{@inheritDoc}*/
  @Override
  public TopicCommand getTopic(final String id) {
    return this.topicCommands.get(id);
  }

  /**{@inheritDoc}*/
  @Override
  public Collection<TopicCommand> getTopics() {
    ArrayList<TopicCommand> values = new ArrayList<TopicCommand>(this.topicCommands.size());
    values.addAll(this.topicCommands.values());
    return values;
  }

  /**{@inheritDoc}*/
  @Override
  public void removeTopic(TopicCommand topicToRemove) {
    this.topicCommands.remove(topicToRemove);
    updateTopics();
  }

  // TODO don't really like the behaviour in case the lock cannot be accquired - should at least re-try
  private synchronized void updateTopics() {
    LockableFileWriter lock = null;
    try {
      lock = new LockableFileWriter(this.lockFile);
      FileWriter writer = null;
      try {
        writer = new FileWriter(this.topicFilename);
        ObjectFactory factory = new ObjectFactory();
        Topics topics = factory.createTopics();

        for (TopicCommand toco : this.topicCommands.values()) {

          Topic topic = factory.createTopic();
          topic.setTopic(toco.getTopic());

          Queries queries = factory.createQueries();
          queries.getQuery().addAll(toco.getQueries());
          topic.setQueries(queries);

          topics.getTopic().add(topic);
        }

        TopicsUtil.marshal(writer, topics);
      } catch (JAXBException e) {
        if(!LOG.isInfoEnabled()) {
          LOG.warn("Could not update topics file. If you see that error for each file update, contact the developer of your choice. Enable info logging to see the stack trace.");
        } else {
          LOG.info("Could not update topics file. If you see that error for each file update, contact the developer of your choice. Stack trace: ", e);
        }
      } catch (IOException e) {
        if(!LOG.isInfoEnabled()) {
          LOG.warn("Could not write updated topics file. If you see that error for each file update, contact the developer of your choice. Enable info logging to see the stack trace.");
        } else {
          LOG.info("Could not write updated file. If you see that error for each file update, contact the developer of your choice. Stack trace: ", e);
        }
      } finally {
        if (writer != null) IOUtils.closeQuietly(writer);
      }
    } catch (IOException e) {
      LOG.warn("Unable to store update to topics to disk - probably someone else is accessing the file we want to update. Storing the update after the next changes. " + e.getMessage());
      LOG.info("Unable to store update to topics to disk: ", e);
    } finally {
      if (lock != null) IOUtils.closeQuietly(lock);
    }
  }

  @PostConstruct
  // TODO don't really like the behaviour in case the lock cannot be accquired - should at least re-try
  public void postConstruct() throws IOException, JAXBException {
    LockableFileWriter lock = null;
    try {
      lock = new LockableFileWriter(this.lockFile);
      FileReader reader = null;
      try {
        reader = new FileReader(this.topicFilename);
        Topics topics = TopicsUtil.unmarshal(reader);

        // convert topics from xml into topiccommands.
        for (Topic topic : topics.getTopic()) {
          TopicCommand toco = new TopicCommand(topic);
          put(toco);
        }
      } finally {
        if (reader != null)
          IOUtils.closeQuietly(reader);
      }
    } catch (IOException e) {
      LOG.error("Unable to load topics from disk - probably someone else is accessing the file we want to update. Storing the update after the next changes. " + e.getMessage());
      LOG.error("Unable to load topics from disk: ", e);
      throw new IllegalStateException("Unable to load existing topic configuration from disk. Is someone else accessing it concurrently?", e);
    } finally {
      if (lock != null) IOUtils.closeQuietly(lock);
    }
  }

  /** Making adding new topics a little easier. */
  private void put(final TopicCommand command) {
    this.topicCommands.put(command.getTopic(), command);
  }
}
